<template>

    <div id="app">
        <div class="chat-container">
            <!-- 左侧联系人列表 -->
            <div class="contacts-sidebar">

                <div class="contacts-list">
                    <!-- 将v-for放在这里内部的每个contact-item上 -->
                    <div v-for="contact in filteredContacts" :key="contact.appointmentId" class="contact-item"
                        :class="{ active: activeContact === contact.appointmentId }" @click="setActiveContact(contact)">
                        <div class="contact-avatar">{{ contact.userName.charAt(0) }}</div>
                        <div class="contact-info">
                            <div class="contact-header">
                                <div class="contact-name">{{ contact.userName }}</div>
                                <div class="contact-time">
                                    {{ formatTime(contact.appointmentTime) }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧聊天区域 -->
            <div class="chat-main">
                <div class="chat-header">
                    <div class="contact-avatar" style="background-color: #e6a23c">{{ carddata.userName.charAt(0)
                    }}
                    </div>
                    <div class="chat-title">{{ carddata.userName }}</div>
                </div>

                <div class="messages-container" ref="messagesContainer">
                    <div v-for="(msg, index) in messages" :key="index"
                        :class="['message', msg.sender === '我' ? 'me' : 'other']">
                        <div class="message-content">{{ msg.content }}</div>
                        <div class="message-status">{{ formatTime(msg.timestamp) }}</div>
                    </div>
                </div>

                <div class="input-area">
                    <div class="input-toolbar">
                        <div class="input-actions">
                            <el-tooltip content="表情" effect="light">
                                <el-button icon="el-icon-s-promotion" circle size="mini"></el-button>
                            </el-tooltip>
                            <el-tooltip content="图片" effect="light">
                                <el-button icon="el-icon-picture" circle size="mini"></el-button>
                            </el-tooltip>
                            <el-tooltip content="文件" effect="light">
                                <el-button icon="el-icon-document" circle size="mini"></el-button>
                            </el-tooltip>
                            <el-tooltip content="语音" effect="light">
                                <el-button icon="el-icon-microphone" circle size="mini"></el-button>
                            </el-tooltip>
                        </div>
                        <div class="input-actions" style="flex:1;text-align:right">
                            <el-tooltip content="聊天记录" effect="light">
                                <el-button icon="el-icon-time" circle size="mini"></el-button>
                            </el-tooltip>
                        </div>
                    </div>

                    <div>
                        <el-input type="textarea" :rows="3" placeholder="输入消息..." v-model="messageText"
                            @keyup.ctrl.enter="sendMessage">
                        </el-input>
                    </div>

                    <div style="display: flex; justify-content: flex-end; margin-top: 12px;">
                        <el-button type="primary" size="small" class="send-button" @click="sendMessage">发送</el-button>
                    </div>
                </div>
            </div>



            <div class="medical-record-container" style="width: 50%;">
                <div class="record-header">
                    <div class="patient-avatar">{{ carddata.userName.charAt(0)
                    }}</div>
                    <div class="patient-info">
                        <div class="patient-meta">
                            <div class="meta-item">
                                <i>姓名:{{ carddata.userName }}</i>
                            </div>
                            <div class="meta-item">
                                <i>性别:{{ carddata.userGender }}</i>
                            </div>
                            <div class="meta-item">
                                <i>就诊号:{{ carddata.medicalRecordNumber }}</i>
                            </div>
                            <div class="meta-item">
                                <i>电话:{{ carddata.userPhoneNumber }}</i>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="record-content">

                    <div class="content-right">
                        <div class="section">
                            <div class="section-title">
                                <i class="el-icon-notebook-2"></i>AL初步判断
                            </div>
                            <div class="section-content">
                                <p>干代：以利钠、和果糖3天，行右心室修，进食后症状加重。</p>
                            </div>
                        </div>


                        <div class="section">
                            <div class="section-title">
                                <i class="el-icon-search"></i>病人描述
                            </div>
                            <div class="section-content">
                                <P>{{ carddata.patientDescription }}</P>
                            </div>
                        </div>

                        <div class="section">
                            <div class="section-title">
                                <i class="el-icon-document-checked"></i> 诊查结果
                            </div>
                            <div class="section-content">
                                <el-input v-model="carddata.medicalRecord">{{ carddata.medicalRecord }}</el-input>
                            </div>
                        </div>


                        <div class="section">
                            <div class="section-title">
                                <i class="el-icon-takeaway-box"></i> 处方药物
                            </div>
                            <div class="medication-table">
                                <el-input style="width: 50%;" v-model="medicineNameValue"></el-input>
                                <el-button type="success" @click="searchMedicine">搜索药品</el-button>
                                <div class="medication-header">
                                    <div class="cell">药品名称</div>
                                    <div class="cell">分类</div>
                                    <div class="cell">数量</div>
                                    <div class="cell">用法</div>
                                    <div class="cell">价格</div>
                                    <div class="cell">选择</div>
                                </div>
                                <div class="medication-row" v-for="(item, index) in medicines" :key="index">
                                    <div class="cell">{{ item.medicineName }}</div>
                                    <div class="cell">{{ item.medicineDescription }}</div>
                                    <div class="cell">{{ item.medicineNumber }}</div>
                                    <div class="cell">{{ item.medicineDosage }}</div>
                                    <div class="cell">{{ item.medicinePrice }}</div>
                                    <div class="cell">
                                        <el-button type="danger" @click="selectMedicine(item)">选择药品</el-button>
                                    </div>
                                </div>
                            </div>

                            <div class="section">
                                <div class="section-title">
                                    <i class="el-icon-edit-outline"></i> 医生意见
                                </div>
                                <div class="section-content">
                                    <!-- 修改为自适应高度的文本域 -->
                                    <el-input type="textarea" v-model="carddata.doctorOpinion"
                                        :autosize="{ minRows: 3, maxRows: 10 }" resize="none" placeholder="请输入医生意见"
                                        @input="adjustTextareaHeight"></el-input>
                                </div>
                            </div>

                        </div>

                        <div class="doctor-signature">
                            <el-button type="danger" @click="UploadRecord">确认提交</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

    </div>

</template>

<script>
import { queryName, changeCard, insertMessage, queryMedicine, createOrder } from '../../api/visit/all';
export default {
    data() {
        return {
            // 为每个联系人存储独立的消息记录
            chatHistory: {},
            // 当前选中的联系人ID
            activeContactId: null,
            // 当前展示的消息列表
            currentMessages: [],


            medicines: [],
            activeUserId: null,
            medicineNameValue: '',
            searchName: '',
            activeContact: '1',
            messageText: '',
            selectedMedicine: null,
            contacts: [],
            medical: {
                medicineName: '',
                medicineDescription: '',
                medicineNumber: '',
                medicineDosage: '',
                medicinePrice: ''

            },
            carddata: {
                userName: '',
                userGender: '',
                medicalRecordNumber: '',
                userPhoneNumber: '',
                doctorOpinion: '',
                medicalRecord: '',
                patientDescription: ''
            },
            messages: [] // 可添加实际消息数据
        }
    },
    computed: {
        filteredContacts() {
            const today = new Date().toISOString().split('T')[0]; // 获取当天日期[6,7](@ref)

            // 首先过滤出当天预约的联系人
            let todayContacts = this.contacts.filter(contact => {
                if (!contact.appointmentTime) return false;
                const appointmentDate = new Date(contact.appointmentTime).toISOString().split('T')[0];
                return appointmentDate === today;
            });

            // 应用搜索条件
            if (this.searchName) {
                const searchLower = this.searchName.toLowerCase();
                todayContacts = todayContacts.filter(contact =>
                    contact.userName?.toLowerCase().includes(searchLower)
                );
            }

            return todayContacts;
        },
        activeContactObj() {
            // 使用 medicalRecordId 匹配 [7](@ref)
            return this.contacts.find(c =>
                c.medicalRecordId == this.activeContact
            ) || { userName: "" }; // 提供安全的默认值
        }
    },
    methods: {

        // 生成订单号函数
        generateOrderNumber() {
            // 1. 固定前缀
            const prefix = "MO";

            // 2. 获取当前日期（YYYYMMDD格式）
            const date = new Date();
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0'); // 补零[6,7](@ref)
            const day = String(date.getDate()).padStart(2, '0'); // 补零[6,7](@ref)
            const datePart = `${year}${month}${day}`; // 输出如 20250820

            // 3. 生成3位随机序列号（范围100-999）[9,10](@ref)
            const randomSeq = Math.floor(100 + Math.random() * 900);

            // 4. 组合完整订单号
            return `${prefix}${datePart}${randomSeq}`;
        },
        formatTime(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
        },
        // 自适应调整文本域高度
        adjustTextareaHeight() {
            this.$nextTick(() => {
                const textarea = this.$refs.doctorOpinionTextarea;
                if (textarea) {
                    textarea.style.height = 'auto';
                    textarea.style.height = `${Math.min(textarea.scrollHeight, 300)}px`;
                }
            });
        },


        selectMedicine(medicine) {
            this.selectedMedicine = medicine;
            // 构建药品信息字符串
            const medicineInfo = `
            药品名称:${medicine.medicineName} 
            分类：${medicine.medicineDescription} 
            数量：${medicine.medicineNumber} 
            用法：${medicine.medicineDosage}
        `;

            // 添加到医生意见输入框（保留原有内容）
            if (this.carddata.doctorOpinion) {
                this.carddata.doctorOpinion += medicineInfo;
            } else {
                this.carddata.doctorOpinion = medicineInfo;
            }
        },


        // 查询药品
        searchMedicine() {
            let param = {
                medicineName: this.medicineNameValue
            }
            queryMedicine(param).then((res => {
                console.log(res)
                if (res.data[0] != null) {
                    this.medicines = res.data
                } else {
                    this.$message({
                        message: '没有该药品',
                        type: 'error'
                    });
                }

            }))
        },
        // 切换卡片信息
        changeCard(userId) {
            console.log("当前用户ID:", userId);
            let params = { userId: userId };
            changeCard(params).then((res => {
                console.log(res)

                this.carddata = {
                    userName: res.rows[0].userName,
                    userGender: res.rows[0].userGender,
                    medicalRecordNumber: res.rows[0].medicalRecordNumber,
                    userPhoneNumber: res.rows[0].userPhoneNumber,
                    patientDescription: res.rows[0].patientDescription,
                    medicalRecordId: res.rows[0].medicalRecordId,
                    medicalRecord: res.rows[0].medicalRecord,
                    doctorOpinion: res.rows[0].doctorOpinion
                }
            }))

        }
        ,
        seachname() {
            queryName().then((res) => {
                console.log(res)
                this.contacts = res.rows
            })
        },



        setActiveContact(contact) {
            this.activeContactId = contact.appointmentId;
            this.changeCard(contact.userId);

            // 初始化消息记录
            if (!this.chatHistory[contact.appointmentId]) {
                this.chatHistory[contact.appointmentId] = [];
            }
            this.currentMessages = this.chatHistory[contact.appointmentId];
        },


        sendMessage() {
            const newMsg = {
                sender: '我',
                content: this.messageText,
                timestamp: new Date()
            };

            // 添加到当前联系人的历史记录
            this.chatHistory[this.activeContactId].push(newMsg);
            this.currentMessages = this.chatHistory[this.activeContactId];

            // WebSocket发送（文档8）
            this.socket.send(JSON.stringify({
                Toname: this.activeContactObj.userName,
                Message: this.messageText
            }));
        },


        UploadRecord() {
            let params = {
                medicalRecord: this.carddata.medicalRecord,
                doctorOpinion: this.carddata.doctorOpinion,
                medicalRecordId: this.carddata.medicalRecordId,
            }
            insertMessage(params).then((res => {
                if (res.code == 200) {
                    this.$message({
                        showClose: true,
                        message: '提交成功',
                        type: 'success'
                    });
                    this.changeCard();
                }
            }));

            // 创建药品订单
            let data = {
                medicineOrderUserId: this.activeUserId,
                medicineRecordId: this.carddata.medicalRecordId,
                medicineOrderNumber: this.generateOrderNumber(),
                medicineOrderPrice: this.selectedMedicine?.medicinePrice,
                medicineId: this.selectedMedicine?.medicineId,
            }
            createOrder(data).then((res => {
                console.log(res)
            }))
        },

        scrollToBottom() {
            this.$nextTick(() => {
                const container = this.$refs.messagesContainer;
                container.scrollTop = container.scrollHeight;
            });
        },

        initWebSocket() {
            var vue = this;
            //创建websocket
            if (window.WebSocket) {
                vue.ws = new WebSocket("ws://localhost:9191/chat");
            }

            this.socket.onopen = () => {
                console.log("WebSocket连接已建立");
            };

            this.socket.onmessage = (event) => {
                const msg = JSON.parse(event.data);
                if (msg.System) {
                    // 更新在线用户列表
                    const contactId = this.findContactIdByUsername(msg.fromName);
                }
                if (contactId) {
                    // 添加到对应联系人的历史记录
                    this.chatHistory[contactId].push({
                        sender: msg.fromName,
                        content: msg.message,
                        timestamp: new Date()
                    });
                }
                this.scrollToBottom();
            };
        }
    },
    // 可添加mounted或其他生命周期钩子
    mounted() {
        this.seachname();
        this.initWebSocket();
    }
}
</script>

<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
}

#app {
    width: 100%;
    height: 100%;
}

body {
    background-color: #f0f2f5;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
}

.chat-container {
    width: 100%;
    max-width: 1300px;
    height: 100%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    background: white;
    overflow: hidden;
    display: flex;
}

/* 左侧联系人列表 */
.contacts-sidebar {
    width: 170px;
    border-right: 1px solid #e6e6e6;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.search-bar {
    padding: 16px;
    background: white;
}

.contacts-list {
    flex: 1;
    overflow-y: auto;
    border-top: 1px solid #e6e6e6;
}

.contact-item {
    display: flex;
    padding: 16px;
    cursor: pointer;
    transition: background 0.2s;
    border-bottom: 1px solid #f5f5f5;
}

.contact-item:hover {
    background: #f5f7fa;
}

.contact-item.active {
    background: #ecf5ff;
    border-right: 3px solid #409eff;
}

.contact-avatar {
    width: 45px;
    height: 45px;
    border-radius: 50%;
    background: #409eff;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    margin-right: 12px;
}

.contact-info {
    flex: 1;
    overflow: hidden;
}

.contact-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 6px;
}

.contact-name {
    font-weight: 600;
    color: #303133;
    font-size: 15px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.contact-time {
    font-size: 12px;
    color: #909399;
}

.contact-preview {
    font-size: 13px;
    color: #606266;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 右侧聊天区域 */
.chat-main {
    flex: 1;
    display: flex;
    flex-direction: column;
    height: 700px;
}

.chat-header {
    padding: 16px 24px;
    border-bottom: 1px solid #e6e6e6;
    display: flex;
    align-items: center;
}

.chat-title {
    font-size: 18px;
    font-weight: 600;
    margin-left: 12px;
}

.chat-status {
    margin-left: 12px;
    font-size: 13px;
    color: #67c23a;
}

.messages-container {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background: #f5f7fa;
    background-image: linear-gradient(rgba(245, 245, 245, 0.6), rgba(245, 245, 245, 0.6)),
        url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200"><rect width="100%" height="100%" fill="transparent"/><path d="M50 50 L150 50 L150 150 L50 150 Z" stroke="rgba(100,100,100,0.05)" stroke-width="1" fill="none"/></svg>');
}

.time-divider {
    text-align: center;
    margin: 20px 0;
    font-size: 13px;
    color: #909399;
    position: relative;
}

.time-divider span {
    background: #f5f7fa;
    padding: 0 12px;
    position: relative;
    z-index: 2;
}

.time-divider:before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: #e6e6e6;
    z-index: 1;
}

.message {
    display: flex;
    margin-bottom: 18px;
}

.message.me {
    flex-direction: row-reverse;
}

.message-avatar {
    flex-shrink: 0;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #67c23a;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
}

.message-bubble {
    max-width: 65%;
    margin: 0 12px;
    position: relative;
}

.message-content {
    padding: 12px 16px;
    border-radius: 8px;
    line-height: 1.6;
    position: relative;
}

.message.other .message-content {
    background: white;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    border: 1px solid #ebeef5;
}

.message.me .message-content {
    background: #409eff;
    color: white;
}

.message-status {
    font-size: 12px;
    color: #909399;
    margin-top: 4px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.message.me .message-status {
    color: #909399;
}

.message-toolbar {
    display: none;
    position: absolute;
    right: 0;
    top: -25px;
    background: white;
    border-radius: 15px;
    padding: 3px;
    box-shadow: 0 1px 8px rgba(0, 0, 0, 0.12);
}

.message:hover .message-toolbar {
    display: flex;
}

.input-area {
    padding: 16px;
    background: white;
    border-top: 1px solid #e6e6e6;
}

.input-toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
}

.input-actions {
    display: flex;
}

.send-button {
    margin-left: 10px;
}

.message img {
    max-width: 300px;
    border-radius: 4px;
    margin-top: 5px;
}



.medical-record-container {
    max-width: 1200px;
    margin: 0 auto;
    background: white;
    border-radius: 12px;
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12);
    overflow: hidden;
    float: right;
}

.record-header {
    background: linear-gradient(to right, #409eff, #1d62f0);
    color: white;
    padding: 10px 15px;
    display: flex;
    align-items: center;
    position: relative;
    box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.patient-avatar {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: white;
    color: #409eff;
    font-size: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    border: 3px solid rgba(255, 255, 255, 0.5);
}

.patient-info {
    flex: 1;
}

.patient-info h1 {
    font-size: 28px;
    font-weight: 600;
    margin-bottom: 8px;
    letter-spacing: 1px;
}

.patient-meta {
    display: flex;
    flex-wrap: wrap;
    font-size: 16px;
    margin-bottom: 8px;
}

.meta-item {
    margin-right: 25px;
    display: flex;
    align-items: center;
}

.meta-item i {
    margin-right: 8px;
    font-size: 18px;
}

.record-status {
    padding: 8px 16px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
}

.record-content {
    display: flex;
    padding: 0;
}


.content-right {
    flex: 1;
    padding: 25px 30px;
}

.section {
    margin-bottom: 30px;
}

.section-title {
    font-size: 18px;
    font-weight: 600;
    color: #409eff;
    padding-bottom: 12px;
    margin-bottom: 20px;
    border-bottom: 2px solid #409eff;
    display: flex;
    align-items: center;
}

.section-title i {
    margin-right: 10px;
    font-size: 20px;
}

.section-content {
    font-size: 15px;
    line-height: 1.8;
    color: #4a5568;
}

.diagnosis-item {
    margin-bottom: 20px;
    padding-left: 20px;
    position: relative;
}

.diagnosis-item:before {
    content: '';
    position: absolute;
    left: 0;
    top: 10px;
    width: 8px;
    height: 8px;
    background: #67c23a;
    border-radius: 50%;
}

.diagnosis-title {
    font-weight: 600;
    margin-bottom: 8px;
    color: #303133;
}

.medication-table {
    width: 100%;
    margin-top: 20px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.medication-header {
    display: flex;
    background: #f5f7fa;
    font-weight: 600;
    color: #303133;
    border-bottom: 1px solid #ebeef5;
}

.medication-row {
    display: flex;
    border-bottom: 1px solid #ebeef5;
}

.medication-row:last-child {
    border-bottom: none;
}

.cell {
    padding: 15px;
    flex: 1;
    text-align: center;
}

.cell:first-child {
    text-align: left;
    flex: 2;
}

.dosage-instructions {
    padding: 25px;
    background: #f8f9fe;
    border-radius: 8px;
    margin-top: 25px;
}

.tag-success {
    display: inline-block;
    padding: 4px 12px;
    background: #f0f9eb;
    color: #67c23a;
    border-radius: 4px;
    font-size: 13px;
    margin: 0 5px;
}

.tag-warning {
    display: inline-block;
    padding: 4px 12px;
    background: #fdf6ec;
    color: #e6a23c;
    border-radius: 4px;
    font-size: 13px;
    margin: 0 5px;
}

.doctor-signature {
    margin-top: 30px;
    text-align: right;
    padding-top: 30px;
    border-top: 1px dashed #dcdfe6;
}

.signature-box {
    display: inline-block;
    text-align: center;
}

.signature {
    font-family: 'Brush Script MT', cursive;
    font-size: 28px;
    color: #409eff;
    margin-top: 10px;
}


/* 添加在style部分 */
.section-content .el-textarea__inner {
    resize: none;
    /* 禁止手动调整大小 */
    overflow-y: auto !important;
    /* 确保滚动条显示 */
    min-height: 100px;
    /* 最小高度 */
    max-height: 300px;
    /* 最大高度 */
    transition: height 0.2s ease;
    /* 平滑过渡效果 */
}
</style>
